package com.radar.task.gy;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.radar.common.DateConstants;
import com.radar.common.ProductType;
import com.radar.io.CinradRadar;
import com.radar.task.cd.Constants;
import com.radar.visualize.RasterMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Component
@Slf4j
@Service(value = "ProcessTask")
public class ProcessTask {

//    @Scheduled(cron = "0 0/2 * * * ? ")

    /**
     * 覆盖代码注释
     */
    public void jobRun() {
        long time = new Date().getTime();
        List<File> files = FileUtil.loopFiles(Constants.rootPath + File.separator).stream().filter(i -> Pattern.matches("^Z_RADR_I_Z(\\d{4})_(\\d{14})_O_DOR_(.*?)_CAP_FMT.(bin.bz2|bin)$", i.getName()))
                .sorted(Comparator.comparingLong(i -> Long.parseLong(i.getName().split("_")[4])))
                .filter(i -> Math.abs(time - Long.parseLong(i.getName().split("_")[4])) < 1000 * 60 * 60 * 48)
                .collect(Collectors.toList());
        for (File file : files) {
            File OKFile = new File(Constants.tmpPath + File.separator + "OK" + File.separator + file.getName() + ".OK");
            if (OKFile.exists()) {
                continue;
            }
            File dateTxt = new File(Constants.ncPath + File.separator + "date.txt");
            String dateContent = "";
            if (FileUtil.exist(dateTxt)) {
                dateContent = FileUtil.readString(dateTxt, Charset.defaultCharset());
            }
            process(file);
            String[] split = dateContent.split(",");
            String rdt = "";
            for (int i = 0; i < split.length; i++) {
                if (i == 0 && split.length >= 120) {
                    continue;
                }
                if(split[i].equals("")){
                    continue;
                }
                rdt += split[i] + ",";
            }
            Date dt = DateUtil.parse(file.getName().split("_")[4], DateConstants.DATE_TIME_FORMAT_YYYYMMDDHHMISS);
            rdt += dt.getTime();
            FileUtil.writeString(rdt, dateTxt, Charset.defaultCharset());
            FileUtil.touch(OKFile);
        }
    }

    /**
     * 覆盖代码注释
     * @param file
     */
    public void process(File file) {
        String station = file.getName().split("_")[3];
        String date = file.getName().split("_")[4];
        Date dt = DateUtil.parse(date, com.radar.common.DateConstants.DATE_TIME_FORMAT_YYYYMMDDHHMISS);
        log.info("start parse file : {} , station : {}, date: {}", file.getAbsolutePath(), station, date);
        CinradRadar cinradRadar = new CinradRadar();
        long time = System.currentTimeMillis();
        // out dir
        String outDir = Constants.ncPath +
                File.separator +
                DateUtil.format(dt, com.radar.common.DateConstants.DATE_FORMAT_YYYYMMDD) +
                File.separator +
                station +
                File.separator;
        FileUtil.mkdir(outDir);
        String ncFile = outDir +
                DateUtil.format(dt, com.radar.common.DateConstants.DATE_FORMAT_YYYYMMDDHHMM) + ".nc";
        try {
            // set nc File
            cinradRadar.setNetcdfFile(ncFile);
            cinradRadar.parse(file.getAbsolutePath());
            RasterMap rasterMap = new RasterMap(cinradRadar.radar);
            BufferedImage bufferedImage = rasterMap.simpleCR(RasterMap.buildRasterInfo(ProductType.REF).backColor(new Color(0, 0, 0, 0)));
            ImageIO.write(bufferedImage, "png", new File(outDir + DateUtil.format(dt, com.radar.common.DateConstants.DATE_FORMAT_YYYYMMDDHHMM) + ".png"));
            log.info("start forecast station: {},date : {},path : {}", station, DateUtil.format(dt, com.radar.common.DateConstants.DATE_FORMAT_YYYYMMDDHHMM), file);
            cinradRadar.radar.dispose();
        } catch (Exception e) {
            log.error("start error parse file : {} , station : {}, date: {}", file.getAbsolutePath(), station, date);
            if (cinradRadar.radar != null) {
                cinradRadar.radar.dispose();
            }
            e.printStackTrace();
        }
        log.info("start parse end time : {} ,residue: {},file : {} , station : {}, date: {}", (System.currentTimeMillis() - time) / 1000.0, Constants.singleQueue.size(), file.getAbsolutePath(), station, date);
    }
}
